#include "zf_common_headfile.h"

 // 全局变量定义
Motor motor1 = {
    .dir_device = "/dev/zf_driver_gpio_motor_1",
    .pwm_device = "/dev/zf_device_pwm_motor_1",
    .current_duty = 0,
};

Motor motor2 = {
    .dir_device = "/dev/zf_driver_gpio_motor_2",
    .pwm_device = "/dev/zf_device_pwm_motor_2",
    .current_duty = 0,
};


int16 max_speed_duty = 7000; // 默认最大速度
int16 min_speed_duty = 1500; // 默认最小速度


/**
  * @brief 初始化单个电机
  * @param motor 电机结构体指针
  */
 static void Motor_init(Motor* motor) {
    // 获取PWM设备信息
    pwm_get_dev_info(motor->pwm_device, &motor->pwm_info);
    // 设置默认方向(正向)
    gpio_set_level(motor->dir_device, 1);
    // 停止电机
    pwm_set_duty(motor->pwm_device, 0);

}
 
 /**
  * @brief 设置单个电机速度
  * @param motor 电机结构体指针
  * @param duty 占空比，负值表示反转
  */
 static void Motor_setSpeed(Motor* motor, int16 duty) {
     // 限制速度不超过最大设置值
     if(duty > max_speed_duty) {
         duty = max_speed_duty;
     }
     if(duty < -max_speed_duty) {
         duty = -max_speed_duty;
     }
     
     // 根据正负设置方向和占空比
     if(duty >= 0) {
         gpio_set_level(motor->dir_device, 1); // 正向
         pwm_set_duty(motor->pwm_device, duty);
     } else {
         gpio_set_level(motor->dir_device, 0); // 反向
         pwm_set_duty(motor->pwm_device, -duty);
     }
     
     // 更新当前占空比
     motor->current_duty = duty;
 }
 
 /**
  * @brief 停止单个电机
  * @param motor 电机结构体指针
  */
 static void Motor_stop(Motor* motor) {
     pwm_set_duty(motor->pwm_device, 0);
     motor->current_duty = 0;
 }
 
 
 // 公共接口实现
 void MotorController_initialize() {
     Motor_init(&motor1);
     Motor_init(&motor2);
     atexit(MotorController_cleanup);
     signal(SIGINT, MotorController_sigintHandler);
 }
 
 void MotorController_cleanup() {
     printf("执行清理操作，停止所有电机\n");
     MotorController_stopAll();
 }
 
 void MotorController_sigintHandler(int signum) {
     printf("收到Ctrl+C，程序即将退出\n");
     MotorController_cleanup();
     exit(0);
 }
 

 
 void MotorController_setLeftMotor(int16 speed) {
     Motor_setSpeed(&motor1, speed);
 }
 
 void MotorController_setRightMotor(int16 speed) {
     Motor_setSpeed(&motor2, speed);
 }
 
 void MotorController_setMotors(int16 leftSpeed, int16 rightSpeed) {
     Motor_setSpeed(&motor1, leftSpeed);
     Motor_setSpeed(&motor2, rightSpeed);
 }
 
 void MotorController_stopAll() {
     Motor_stop(&motor1);
     Motor_stop(&motor2);
 }
 

